<!--
 * @Author: fisher
 * @Date: 2021-10-25 18:05:40
 * @LastEditTime: 2021-11-10 00:27:43
 * @LastEditors: fisher
 * @Description: 
 * @FilePath: \d3\src\components\test1.vue
-->
<template>
  <div>
    <svg width="1600" height="800" id="main_svg" class="svgs"></svg>
  </div>
</template>

<script setup>
import { inject, onMounted } from "@vue/runtime-core";

const d3 = inject("d3");

const data = [
  { name: "aaa", value: 3 },
  { name: "bbb", value: 9 },
  { name: "ccc", value: 12 },
  { name: "ddd", value: 5 },
  { name: "eee", value: 1 },
];
onMounted(() => {
  const svg = d3.select("#main_svg");

  const width = +svg.attr("width");
  const height = +svg.attr("height");
  const margin = {
    top: 60,
    right: 30,
    bottom: 60,
    left: 50,
  };
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;
  console.log(width, height);
  const xScale = d3
    .scaleLinear()
    .domain([0, d3.max(data, (item) => item.value)])
    .range([0, innerWidth]);
  const yScale = d3
    .scaleBand()
    .domain(data.map((item) => item.name))
    .range([0, innerHeight])
    .padding(0.1);
  const g = svg
    .append("g")
    .attr("id", "mainGroup")
    .attr("transform", `translate(${margin.left},${margin.top})`);
  const xAxis = d3.axisBottom(xScale);
  const yAxis = d3.axisLeft(yScale);
  g.append("g").call(yAxis);
  g.append("g").call(xAxis).attr("transform", `translate(0,${innerHeight})`);
  data.forEach((item) => {
    g.append("rect")
      .attr("width", xScale(item.value))
      .attr("height", yScale.bandwidth(0.2))
      .attr("fill", "#f4d3a6")
      .attr("y", yScale(item.name));
  });
});
</script>
<style  scoped>
</style>